/**
 * Collections API 服务层
 * 封装所有与 Collection 相关的 API 调用
 */
import { apiClient, ApiResponse } from './client';
import {
  CollectionDto,
  CollectionWithBindingDto,
  CollectionWithTabsDto,
  CreateCollectionRequest,
  UpdateCollectionRequest,
  AttachCollectionRequest,
  ReorderCollectionsRequest,
  SpaceCollectionBindingDto,
  DeleteResponse,
} from './types';

/**
 * 在空间下创建集合
 * POST /spaces/{space_id}/collections
 */
export async function createCollection(
  spaceId: number,
  data: CreateCollectionRequest
): Promise<CollectionWithBindingDto> {
  const response = await apiClient.post<ApiResponse<CollectionWithBindingDto>>(
    `/spaces/${spaceId}/collections`,
    data
  );
  if (!response.data.data) {
    throw new Error('创建集合失败');
  }
  return response.data.data;
}

/**
 * 获取空间下的集合列表及其标签页
 * GET /spaces/{space_id}/collections
 *
 * @description 该接口返回聚合数据，包含集合、空间绑定关系和标签页列表
 * @returns CollectionWithTabsDto[] 包含 items 字段的集合列表
 */
export async function getCollectionsBySpace(
  spaceId: number
): Promise<CollectionWithTabsDto[]> {
  const response = await apiClient.get<ApiResponse<CollectionWithTabsDto[]>>(
    `/spaces/${spaceId}/collections`
  );
  return response.data.data || [];
}

/**
 * 更新集合
 * PATCH /collections/{collection_id}
 */
export async function updateCollection(
  collectionId: number,
  data: UpdateCollectionRequest
): Promise<CollectionDto> {
  const response = await apiClient.patch<ApiResponse<CollectionDto>>(
    `/collections/${collectionId}`,
    data
  );
  if (!response.data.data) {
    throw new Error('更新集合失败');
  }
  return response.data.data;
}

/**
 * 删除集合（软删除）
 * DELETE /collections/{collection_id}
 */
export async function deleteCollection(collectionId: number): Promise<void> {
  await apiClient.delete<ApiResponse<DeleteResponse>>(`/collections/${collectionId}`);
}

/**
 * 关联集合到空间
 * POST /spaces/{space_id}/collections/attach
 */
export async function attachCollectionToSpace(
  spaceId: number,
  data: AttachCollectionRequest
): Promise<SpaceCollectionBindingDto> {
  const response = await apiClient.post<ApiResponse<SpaceCollectionBindingDto>>(
    `/spaces/${spaceId}/collections/attach`,
    data
  );
  if (!response.data.data) {
    throw new Error('关联集合到空间失败');
  }
  return response.data.data;
}

/**
 * 重排序空间下的集合
 * PATCH /spaces/{space_id}/collections/reorder
 *
 * @returns 返回被排序的集合列表（包含collection和binding信息）
 */
export async function reorderCollections(
  spaceId: number,
  data: ReorderCollectionsRequest
): Promise<CollectionWithBindingDto[]> {
  const response = await apiClient.patch<ApiResponse<CollectionWithBindingDto[]>>(
    `/spaces/${spaceId}/collections/reorder`,
    data
  );
  return response.data.data || [];
}
